<?php if (! defined('APPPATH')) die('No direct script access allowed');
/**
 * RENARTI IK
 * An open source application development framework for PHP 5.2.0 or newer
 *
 * @package		RtiFramework
 * @author		Nauris Dambis <nauris.dambis@renarti.com>
 * @copyright	Copyright (c) 2012, RENARTI IK.
 * @license		http://renarti.com/#license
 * @link		http://renarti.com
 * @since		Version 1.0
 */

class RtiSession
{
	protected $_encode;
	
	public function __construct()
	{
		$this->_encode = Rti::config('config')->get('SESSION_ENCODE');
		
		$this->start();
	}
	
	public function start()
	{
		if ($this->id() == '')
		{
			session_start();	
		}
	}
	
	public function destroy()
	{
		session_destroy();		
	}
	
	public function regenerate($delete = FALSE)
	{
		session_regenerate_id($delete);		
	}
	
	public function unsetAll()
	{
		$keys = array_keys($_SESSION);
		
		foreach ($keys as $key)
		{
			$this->delete($key);
		}
		
		session_unset();
	}
	
	public function id()
	{
		return session_id();
	}
	
	public function get($key)
	{
		if (! isset($_SESSION[$key]))
		{
			return '';
		}
		
		$value = $_SESSION[$key];
		
		if ($this->_encode === TRUE)
		{
			$value = Rti::encoder()->decode($value);
		}
		
		$value = unserialize($value);
		
		return $value;
	}
	
	public function set($key, $value)
	{
		$value = serialize($value);
		
		if ($this->_encode === TRUE)
		{
			$value = Rti::encoder()->encode($value);
		}
		
		$_SESSION[$key] = $value;
	}
	
	public function delete($key)
	{
		if (isset($_SESSION[$key]))
		{
			unset($_SESSION[$key]);
		}
	}

	public function writeFlash($key, $value)
	{
		$key = 'flash:' . $key;
		$this->set($key, $value);
	}
	
	public function readFlash($key)
	{
		$key = 'flash:' . $key;		
		$value = $this->get($key);
		$this->delete($key);
		return $value;
	}
	
}

/* End of file RtiSession.php */
/* Location: ./system/core/RtiSession.php */
